package toy.keli.edic.util

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityCompat.shouldShowRequestPermissionRationale
import androidx.core.content.ContextCompat

class PermissionUtil {
    companion object {
        fun getPermission(ct: Context, requiresPermission: Array<String>,onOk:()->Unit={}): Boolean {
            if (ContextCompat.checkSelfPermission(
                    ct,
                    requiresPermission[0]
                )
                != PackageManager.PERMISSION_GRANTED
            ) {
                // 请求权限
                ActivityCompat.requestPermissions(
                    ct as Activity,
                    requiresPermission,
                    1
                )
                ActivityRun.onActivityResult {
                    var isOk = true
                    it.getEntries()?.forEach { entry ->
                        if (entry.value) {
                            // 该权限已授予
                        } else {
                            isOk = false
                            // 该权限被拒绝
//                            if (shouldShowRequestPermissionRationale(permission)) {
//                                // 用户拒绝但未选择"不再询问"，可再次解释需要权限的原因
//                            } else {
//                                // 用户拒绝并选择"不再询问"，引导用户到设置页面
////                                openAppSettings()
//                            }
                        }
                    }
                    if(isOk) onOk()
                }
                return false
            }
            return true
        }
    }
}

private fun ActivityResult.getEntries(): Map<String, Boolean>? {
    val permissions = data?.getStringArrayExtra("permissions") ?: return null
    val grantResults = data?.getIntArrayExtra("grantResults") ?: return null

    // 将数组转换为 List 以便使用 zip 函数
    return permissions.asList().zip(grantResults.toList()) { permission, result ->
        permission to (result == PackageManager.PERMISSION_GRANTED)
    }.toMap()
}
